package xyz.codej.websocket.web.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FastByteArrayOutputStream;
import cn.hutool.extra.qrcode.QrCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import xyz.codej.websocket.netty.server.NettyServer;
import xyz.codej.websocket.utils.SnowFlake;

/**
 * @ClassName: ConsumerController
 * @Description TODO
 * @Author 王华君
 * @Date 2020/4/1 5:29 下午
 * @VERSION 1.0
 */
@Controller
@RequestMapping("/client")
public class ClientController {

    @Autowired
    NettyServer nettyServer;

    /**
     * 登录
     *
     * @param type 1：用户名，2：二维码
     * @return
     */
    @GetMapping("/login")
    public String login(Model model, @RequestParam(required = false) Integer type) {
        if (type == null || type == 2) {
            model.addAttribute("reqId", SnowFlake.generate());
            return "client/login_qrcode";
        } else {
            return "404";
        }
    }

    /**
     * 获取登录二维码
     *
     * @return
     */
    @GetMapping("/login/qrcode")
    @ResponseBody
    public String qrCode(@RequestParam String reqId) {
        FastByteArrayOutputStream outputStream = new FastByteArrayOutputStream();
        QrCodeUtil.generate("https://172.16.40.204:8080/client/auth?reqId=" + reqId, 300, 300, "png", outputStream);
        if (outputStream.size() > 0) {
            String encodedQRCode = Base64.encode(outputStream.toByteArray());
            return "data:image/png;base64," + encodedQRCode;
        }
        return "";
    }

    /**
     * 授权确认页面
     *
     * @param reqId
     * @return
     */
    @GetMapping("/login/auth")
    public String auth(Model model, @RequestParam String reqId) {
        return "client/login_auth";
    }

    /**
     * 授权登录
     *
     * @param model
     * @param reqId
     * @return
     */
    @PostMapping("/login/auth")
    public String doAuth(Model model, @RequestParam String reqId) {
        // 广播
        nettyServer.sendMessage(reqId, "授权成功");
        return "404";
    }
}
